package org.example.petitionplatformsystem.service.Impl;


import org.example.petitionplatformsystem.dao.PetitionEventsRepository;
import org.example.petitionplatformsystem.service.EmotionAnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;

@Service
public class EmotionAnalysisServiceImpl implements EmotionAnalysisService {
    @Autowired
    private PetitionEventsRepository petitionEventsRepository;

    @Override
    public double getSentimentScoreFromPython(String scriptPath, String text) {
        double sentimentScore = 0.0;
        try {
            String pythonInterpreter = "venv\\Scripts\\python.exe"; // 修改为虚拟环境Python解释器的实际路径
            ProcessBuilder pb = new ProcessBuilder(pythonInterpreter, scriptPath, text);
            Process p = pb.start();

            // Capture standard output
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            // Capture error output
            BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            String line;
            while ((line = in.readLine()) != null) {
                sentimentScore = Double.parseDouble(line);
                System.out.println("Sentiment Score: " + sentimentScore);
            }
            in.close();

            // Print error output for debugging
            while ((line = err.readLine()) != null) {
                System.err.println("Error: " + line);
            }
            err.close();

            p.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sentimentScore;
    }
}
